package hbase.client;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;

public class FriendProcessor extends BaseRegionObserver {

    public void postDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException {

        final HTable friend = (HTable) e.getEnvironment().getTable(TableName.valueOf("friend"));

        //解析t1表的插入对象put
        byte[] user = delete.getRow();
        Map<String, byte[]> deleteUsers = delete.getAttributesMap();
        NavigableMap<byte[], List<Cell>> familyCellMap = delete.getFamilyCellMap();

        for (byte[] key: familyCellMap.keySet()) {
            for (Cell cell: familyCellMap.get(key)) {
                Delete newDelete = new Delete(cell.getValueArray());
                newDelete.addFamily(key);
                friend.delete(delete);
            }
        }

        // 如果是删除整条数据，则需要先将用户的所有好友都删除


        /*for (String key : deleteUsers.keySet()) {

            Get get = new Get(Bytes.toBytes(key));

            if (friend.get(get).isEmpty()) {
                continue;
            }
            deleteFriend(friend, key);
        }*/
    }

    public void deleteFriend(HTable table, String rowKey) throws IOException {
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        table.delete(delete);
    }

}
